import time
import datetime
import math
import sqlanydb
import sys
import traceback


g_db = {}

def pos_db(db_cfg):
    c = g_db.get('pos')
    if c != None: return (g_db.get('pos_cur'), g_db.get('pos_sur'))
    c = g_db['pos'] = sqlanydb.connect(**db_cfg)
    cur = g_db['pos_cur'] = c.cursor()
    sur = g_db['pos_sur'] = c.cursor()
    return (cur, sur)

def pos_db_close():
    c = g_db.get('pos')
    if c == None: return
    try:
        c.close()
    except:
        pass
    g_db['pos'] = g_db['pos_cur'] = g_db['pos_sur'] = None

def default_stop_pending(): return 0

def run_srv(db_cfg, func_srv):
    try:
        import pysrv
        stop_pending = pysrv.stop_pending
    except Exception, e:
        print e, "fallback -> default_stop_pending"
        stop_pending = default_stop_pending
    
    print __file__, ' > start'
    
    uts = lts = int( time.time() * 1000 )
    tms = 1500
    ums = tms * 3
    while not stop_pending():
        if int( time.time() * 1000 ) - lts < tms:
            time.sleep(0.2)
            continue
        
        try:
            func_srv( pos_db(db_cfg) )
            
            if int( time.time() * 1000 ) - uts >= ums: uts = int( time.time() * 1000 )
            
        except sqlanydb.Error, e:
            print "sqlanydb.Error", e
            pos_db_close()
            
        except Exception, e:
            print traceback.format_exc()

        lts = int( time.time() * 1000 )

    print "Done"

